package com.weibo4j.api.response.trend;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import com.alibaba.fastjson.JSONObject;
import com.weibo4j.api.WeiboResponse;
import com.weibo4j.api.domain.Trend;
import com.weibo4j.api.json.JSON;

public class TrendsHotResponse extends WeiboResponse<List<Trend>>{
    
    protected List<Trend> model;
    
    public Integer getAsOf() {
        return result.getInteger("as_of");
    }
    
    public Date getDate() {
        JSONObject trends = result.getJSONObject("trends");
        Set<String> keys = trends.keySet();
        if (!keys.isEmpty()) {
            String dt = keys.toArray()[0].toString();
            try {
                return new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(dt);
            } catch (ParseException e) {
            }
        } 
        return null;
    }

    @Override
    public List<Trend> getModel() {
        if (success && model == null) {
            isSuccess();
        }
        return model;
    }

    @Override
    public boolean isSuccess() {
        boolean isSuccess = super.isSuccess();
        if (isSuccess && model == null) {
            JSONObject trends = result.getJSONObject("trends");
            for (Entry<String, Object> entry : trends.entrySet()) {
                model = JSON.parseArray(trends.getString(entry.getKey()), Trend.class);
                break;
            }
        }
        return isSuccess;
    }
}
